/*
 * VisualDiagramComponent.cpp
 *
 *  Created on: May 28, 2013
 *      Author: root
 */

#include "gui/VisualComponents/VisualDiagramComponent.h"
#include "gui/VisualComponents/VisualComponentConector.h"
#include "gui/VisualComponents/der/VisualComponentViaDER.h"
#include "model/Utils.h"
#include "model/Diagram.h"

VisualDiagramComponent::VisualDiagramComponent(Diagram *diagram) {
	m_component = NULL;
	m_diagram = diagram;
	showConnectors = false;
}

VisualDiagramComponent::VisualDiagramComponent(const VisualDiagramComponent &other) {
	m_component = NULL;
	m_diagram = other.m_diagram;
	m_selected = false;
	showConnectors = false;
}

VisualDiagramComponent::~VisualDiagramComponent() {
	m_component->removeFromDiagram(m_diagram);
}

void VisualDiagramComponent::initialize() {
	m_component->addToDiagram(m_diagram);

	conectoresEntrantes.clear();
	conectoresSalientes.clear();

	for(unsigned i = 0; i < m_component->getAttributeConnectors()->size(); i++) {
		VisualComponentConector *visualConnector = new VisualComponentConector(this, (*m_component->getAttributeConnectors())[i], i, true, m_diagram);
		addChild(visualConnector);
		conectoresEntrantes.push_back(visualConnector);
	}
	for(unsigned i = 0; i < m_component->getExitConnectors()->size(); i++) {
		VisualComponentConector *visualConnector = new VisualComponentConector(this,(*m_component->getExitConnectors())[i], i, false, m_diagram);
		addChild(visualConnector);
		conectoresSalientes.push_back(visualConnector);
	}
}

void VisualDiagramComponent::on_move(int mouseX, int mouseY) {
	m_component->setX(mouseX);
	m_component->setY(mouseY);
	for (std::vector<VisualComponent*>::iterator it = m_children.begin(); it != m_children.end(); ++it)
		(*it)->on_move(mouseX, mouseY);
}

void VisualDiagramComponent::on_expose(Cairo::RefPtr<Cairo::Context> ptrContext) {
	update();

	draw(ptrContext);

	if (showConnectors) {
		for (unsigned int i = 0; i < conectoresEntrantes.size(); i++) {
			VisualComponentConector *conector = conectoresEntrantes[i];
			if (conector->getVia() != NULL) {
				conector->on_expose(ptrContext);
			}
		}
	}
}

void VisualDiagramComponent::load(XmlReader& reader, XmlReader& readerModel, Diagram* diagram){
	m_component->deserialize(reader, readerModel);
}

VisualComponentConector *VisualDiagramComponent::getConectorLibre() {
	VisualComponentConector *conectorLibre = NULL;
	for (unsigned int i = 0; i < conectoresEntrantes.size(); i++) {
		VisualComponentConector *conectorI = conectoresEntrantes[i];
		if (conectorI->getVia() == NULL) {
			conectorLibre = conectorI;
			break;
		}
	}
	return conectorLibre;
}
